/****************************************************************
 * <strong>MFMVCServlet</strong>
 *
 * <p>
 * MFMVCServlet
 * </p>
 *
 * @author AndyZhang 2013
 * @version 0.1
 * ToDo:2013-3-3
 ***************************************************************/
package com.thinkwide.data.mvc.servlet;

import com.thinkwide.data.core.MFPath;
import com.thinkwide.data.debug.MFDebug;
import com.thinkwide.data.mvc.config.MFMVCManager;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MFMVCServlet extends HttpServlet {
    private static MFMVCManager manager;

    @Override
    public void init() throws ServletException {
        String mvcConfigLocation = this.getInitParameter("mvcConfigLocation");
        //getServletConfig().getServletContext().getInitParameter("mvcConfigLocation");
        if (manager == null) {
            try {
                manager = new MFMVCManager();
                String path = MFPath.getParentPath(MFPath.getDirFromClassLoader()) + MFPath.fseparator + mvcConfigLocation;
                manager.loadConfig(path);
                MFDebug.println("加载MVC配置文件...");
                manager.scanAnnotation();
                MFDebug.println("扫描MVC注解类...");
                if (manager.isMvc_debug()) manager.getMappingitems().printList();
            } catch (Throwable ex) {
                ex.printStackTrace();
            }
        }


    }

    @Override
    public void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String url = ((HttpServletRequest) request).getRequestURI();

        if (url.endsWith(".do")) {

            try {

                manager.runMapping(url, request, response);
            } catch (Throwable ex) {
                ex.printStackTrace();
                ex.printStackTrace(response.getWriter());
                //response.getWriter().println(ex.printStackTrace(response.getWriter()));
            }
            return;
        } else
            super.service(request, response);

    }

}
